package com.bolehui.base.encrypt.encryptor;

import com.bolehui.base.annotation.SensitiveField;
import com.bolehui.base.encrypt.Encrypt;
import com.bolehui.base.utils.AESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName AESEncrypt
 * @Description
 * @createTime 2024/12/5 14:00
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Component
public class AESEncrypt implements Encrypt {

    @Autowired
    AESUtil aesUtil;

    @Value("${aes.key: yy-4real}")
    private String key;

    @Override
    public <T> T encrypt(Field[] declaredFields, T paramsObject) throws Exception {
        for (Field field : declaredFields) {
            //取出所有被EncryptDecryptField注解的字段
            SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
            if (!Objects.isNull(sensitiveField)) {
                field.setAccessible(true);
                Object object = field.get(paramsObject);
                //暂时只实现String类型的加密
                if (object instanceof String) {
                    String value = (String) object;
                    //加密  这里我使用自定义的AES加密工具
                    field.set(paramsObject, aesUtil.encrypt(value, key));
                }
            }
        }
        return paramsObject;

    }
}
